#-*- coding: utf-8 -*-
from xml.parsers import expat
from util.Location import Location
from util.Metadata import Metadata


'''
Handler sax che genera le Location man mano che viene letto l'xml
'''
class LocationParser(object):
    
    def __init__ (self):
        self.sett = False
        self.textBuf = ''
        self.locations_dict = {}
        self.tmpMetadata = Metadata()
        #work-around per evitare che una tag note messo a cazzo faccia crashiare il programma
        #in altre parole: nell'xml di prova c'è un tag note all'interno dei metadati
        self.tmpLocation = Location()
        
    def start_element(self, name, attrs):
        if name == 'location':
            self.tmpLocation = Location()
            self.tmpLocation.id = (attrs['id'])
            self.tmpLocation.lat = float((attrs['lat']))
            self.tmpLocation.long = float((attrs['long']))
            self.tmpLocation.metadata = self.tmpMetadata
        if name == 'opening' and attrs.has_key('showAs'):
            if 'settimanale' in attrs['showAs']:
                self.sett = True
            
            
    def end_element(self, name):
        self.textBuf = self.textBuf.rstrip()
        if name == 'category':
            self.tmpLocation.category = self.textBuf
        elif name == 'name':
            self.tmpLocation.name = self.textBuf
        elif name == 'address':
            self.tmpLocation.address = self.textBuf
        elif name == 'tel':
            self.tmpLocation.tel = self.textBuf
        elif name == 'opening':
            self.tmpLocation.opening += self.textBuf
            if self.sett:
                self.tmpLocation.opening_settimanale += self.textBuf
                self.sett = False
        elif name == 'closing':
            self.tmpLocation.closing += self.textBuf
        elif name == 'subcategory':
            self.tmpLocation.subcategory = self.textBuf
        elif name == 'note':
            self.tmpLocation.note = self.textBuf
        elif name == 'location':
            self.locations_dict[self.tmpLocation.id] = self.tmpLocation
        elif self.tmpMetadata:
            if name == 'creator':
                self.tmpMetadata.creator = self.textBuf
            elif name == 'created':
                self.tmpMetadata.created = self.textBuf
            elif name == 'version':
                self.tmpMetadata.version = self.textBuf
            elif name == 'source':
                self.tmpMetadata.source = self.textBuf
            elif name == 'valid':
                self.tmpMetadata.valid = self.textBuf
        elif name == 'metadata':
            self.tmpMetadata = None
            
        self.textBuf = ''
        
    def char_data(self, data):
        data = data.strip()
        if data:
            data = data.encode('utf8')
            self.textBuf += data + '\n'
            
    def parse(self, str_xml):
        xmlParser = expat.ParserCreate()
        xmlParser.CharacterDataHandler = self.char_data
        xmlParser.StartElementHandler = self.start_element
        xmlParser.EndElementHandler = self.end_element
        xmlParser.Parse(str_xml)
        
'''
Converte una stringa XML in un Dizionario di Location

@param json_str: Stringa che contiene le location in formato XML
@return: Dizionario che associa Oggetti di tipo Location ai relativi id
@author: Simone Rondelli
'''
def parse_xml(xml_str):
    xText = LocationParser()
    xText.parse(xml_str)
    return xText.locations_dict

'''
Dato un Dizionario di Location crea il relativo xml

@param locations_dict: Dizionario che associa Oggetti di tipo Location ai relativi id
@return: Stringa che contiene il risultato in xml
@author: Simone Rondelli
'''
def write_xml(locations_dict):
    xml = '<?xml version="1.0" encoding="UTF-8"?>\n' 
    xml += '<!DOCTYPE locations SYSTEM "http://vitali.web.cs.unibo.it/twiki/pub/TechWeb12/DTDs/locations.dtd" >\n\n' 
    xml += '<locations>\n'
    write_meta = True
    
    for k in locations_dict.keys():
        loc = locations_dict[k]
        
        if write_meta:
            metadata = loc.metadata
            xml += '\t<metadata>\n'
            xml += '\t\t<creator>' + metadata.creator + '</creator>\n'
            xml += '\t\t<created>' + metadata.created + '</created>\n'
            xml += '\t\t<version>' + metadata.version + '</version>\n'
            xml += '\t\t<source>' + metadata.source + '</source>\n'
            xml += '\t\t<valid>' + metadata.valid + '</valid>\n'
            xml += '\t</metadata>\n'
            write_meta = False
            
        xml += '\t<location id="' + k + '" lat="' + str(loc.lat) + '" long="' + str(loc.long) + '">\n'
        xml += '\t\t<category>' + loc.category + '</category>\n'
        xml += '\t\t<name>' + loc.name + '</name>\n'
        xml += '\t\t<address>' + loc.address + '</address>\n'
        if loc.subcategory:
            xml += '\t\t<subcategory>' + loc.subcategory + '</subcategory>\n'
        if loc.tel:
            xml += '\t\t<tel>' + loc.tel + '</tel>\n'
        if loc.note:
            xml += '\t\t<note>' + loc.note + '</note>\n'
            
        #for closing in loc.closing:
        xml += '\t\t<closing>' + loc.closing + '</closing>\n'
        
        #for opening in loc.opening:
        xml += '\t\t<opening>' + loc.opening + '</opening>\n'

        xml += '\t</location>\n'
    
    xml += '</locations>'
    
    if type(xml) == str:
        xml = unicode(xml,'utf8')
        
    return xml